package com.samphanie.auiu.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.samphanie.auiu.admin.service.ISysRoleResourceService;
import com.samphanie.auiu.mbg.mapper.SysRoleResourceMapper;
import com.samphanie.auiu.mbg.model.SysRoleResource;
import com.samphanie.auiu.mbg.utils.PageUtils;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色资源关系Service业务层处理
 *
 * @author zsy
 * @date 2021-05-18
 */
@Service
public class SysRoleResourceServiceImpl extends ServiceImpl<SysRoleResourceMapper, SysRoleResource> implements ISysRoleResourceService {

    /**
     * 查询角色资源关系列表
     *
     * @param query
     * @return 角色资源关系
     */
    @Override
    public List<SysRoleResource> selectSysRoleResourceList(Map<String, String> query) {
        return baseMapper.selectSysRoleResourceList(query);
    }

    @Override
    public PageUtils listPage(Map<String, Object> query) {
        PageUtils.startPage(query);
        val list = list();
        return new PageUtils(list);
    }

    @Override
    public List<SysRoleResource> listByRoleId(Long roleId) {
        return list(new LambdaQueryWrapper<SysRoleResource>().eq(SysRoleResource::getRoleId, roleId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addRoleResource(Long roleId, Set<Long> resources) {
        boolean result = this.deleteByRoleId(roleId);
        if (CollUtil.isEmpty(resources)) {
            return result;
        }
        Set<SysRoleResource> roleResources = resources.stream()
                .map(item -> SysRoleResource.builder()
                        .roleId(roleId)
                        .resourceId(item)
                        .build()).collect(Collectors.toSet());
        return saveBatch(roleResources);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteByRoleId(Long roleId) {
        return remove(new LambdaQueryWrapper<SysRoleResource>().eq(SysRoleResource::getRoleId, roleId));
    }

}
